package waitAndNotify.cigarette;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author： pang-yun
 * @date： 2021-11-01 11:14
 * 功能目的 ：用于   使用 wait  notify  来 阻塞 线程 和 唤醒线程
 * - 不会阻塞 其他线程
 * - 但是 notify 在唤醒线程时  可能会 错误唤醒其他线程！
 */
@Slf4j
public class TestModify1 {
    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeOut = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                log.info(" has  cigarette? {}", hasCigarette);
                if (!hasCigarette) {
                    log.info("no ! give me a break");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info(" now   has Cigarette? {}", hasCigarette);

                if (hasCigarette) {
                    log.info("now  root begin working!");
                }
            }
        },"吸烟 thread").start();

        for (int i = 1; i < 5; i++) {
            new Thread(() -> {
                synchronized (room) {
                    log.info("others  begin working!!!");
                }
            },"其他人").start();
        }

        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            synchronized (room){
                log.info("give cigarette   let root  work!");
                hasCigarette =true;
                room.notify();
            }
        },"送烟").start();
    }
}
